import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:shop/config/config.dart';
GlobalKey<NavigatorState> navigatorKey = GlobalKey();

class HttpUtil{
  Future<dynamic> get(String url) async{
    // 先获取用户的token
    String token = Config.getInstance().getToken() ;
    // if(token == null){
    //   Config.getInstance().logout();
    //   return ;
    // }
    BaseOptions header = BaseOptions(headers: {"token": "5555"});
    // header
    Dio dio = new Dio(header) ;
    if(url.startsWith("/")) {
      url = url.substring(1) ;
    }
    //print(Config.getInstance().getHost() + url) ;
    try {
      var flag = false ;
      bool success = true ;
      Response response = await dio.get(Config.getInstance().getHost() + url).catchError((res){
        print(res) ;
        if(res.response.statusCode == 401){
          // eventBus.fire(RouteEvent("login"));
          // 清空用户信息
          // navigatorKey.currentState.pushNamedAndRemoveUntil("/login" , ModalRoute.withName("/")) ;
          flag = true ;
          Config.getInstance().logout() ;
          return true ;
        }
        success = false ;
      }) ;
      print("请求状态success:${success}") ;
      if(!success || response == null) {
        return {"code":500 , "msg":"请求异常" , "data":""} ;
      }
      if(response != null) {
        if(response.headers != null) {
          if(response.headers.value("token") != null) {
            if (response.headers.value("token")[0] != null) {
              print("响应token:"+response.headers["token"][0]) ;
              Config.getInstance().setToken(response.headers["token"][0]);
            }
          }
        }
      }
      print(response.data) ;
      if(flag) {
        return {"code":500 , "msg":"登录失效" , "data":""} ;
      }
      if(response.data.runtimeType == String) {
        return JsonCodec().decoder.convert(response.data) ;
      }
      return response.data ;
    } catch (e) {
      print(e) ;
      return {"code":500 , "msg":"网络连接异常" , "data":""} ;
    }finally{
      dio.close() ;
    }
  }

  Future<dynamic> get_sample(String url) async{
    // 先获取用户的token
    String token = Config.getInstance().getToken() ;
    // if(token == null){
    //   Config.getInstance().logout();
    //   return ;
    // }
    BaseOptions header = BaseOptions();
    // header
    Dio dio = new Dio(header) ;
    //print(Config.getInstance().getHost() + url) ;
    try {
      bool success = true ;
      Response response = await dio.get(url).catchError((res){
        print(res) ;
        if(res.response.statusCode == 401){
          // eventBus.fire(RouteEvent("login"));
          // 清空用户信息
          // navigatorKey.currentState.pushNamedAndRemoveUntil("/login" , ModalRoute.withName("/")) ;
          Config.getInstance().logout() ;
          return true ;
        }
        success = false ;
      }) ;
      if(!success || response == null) {
        return {"code":500 , "msg":"请求异常" , "data":""} ;
      }
      if(response.headers != null) {
        if(response.headers.value("token") != null) {
          if (response.headers.value("token")[0] != null) {
            Config.getInstance().setToken(response.headers["token"][0]);
          }
        }
      }
      print(response.data) ;
      return response.data ;
    } catch (e) {
      print(e) ;
      return "" ;
    }finally{
      dio.close() ;
    }
  }

  Future<dynamic> get_dy(String url) async{
    // 先获取用户的token
    String token = Config.getInstance().getToken() ;
    // if(token == null){
    //   Config.getInstance().logout();
    //   return ;
    // }
    BaseOptions header = BaseOptions(headers: {"token": token});
    // header
    Dio dio = new Dio(header) ;
    if(url.startsWith("/")) {
      url = url.substring(1) ;
    }
    if(Config.getInstance().getDyHost() == null) {
      await getDyUrl() ;
    }
    print(Config.getInstance().getDyHost() + url) ;
    try {
      Response response = await dio.get(Config.getInstance().getDyHost() + url).catchError((res){
        // 请求结果异常
        print(res) ;
        if(res.response.statusCode == 401){
          // eventBus.fire(RouteEvent("login"));
          // 清空用户信息
          // navigatorKey.currentState.pushNamedAndRemoveUntil("/login" , ModalRoute.withName("/")) ;
          Config.getInstance().logout() ;
        }
      }).timeout(Duration(seconds: 5) , onTimeout: (){
        // 超时
      }) ;
      if(response == null) {
        return {"code":500 , "msg":null , "data":""} ;
      }
      print(response.data) ;
      if(response.headers != null) {
        if(response.headers.value("token") != null) {
          if (response.headers.value("token")[0] != null) {
            Config.getInstance().setToken(response.headers["token"][0]);
          }
        }
      }
      if(response.data.runtimeType == String) {
        return JsonCodec().decoder.convert(response.data) ;
      }
      if(response.data["code"] == 401) {
        Config.getInstance().logout() ;
      }
      return response.data ;
    } catch (e) {
      print(e) ;
      return {"code":500 , "msg":"请求出错" , "data":""} ;
    }finally{
      dio.close() ;
    }
  }

  void getDyUrl() async{
    await Future.delayed(Duration(seconds: 1)) ;
    if(Config.getInstance().getDyHost() == null) {
      getDyUrl() ;
    }else{
      return ;
    }
  }

  Future<dynamic> upload(String url , File file , {onProcess}) async{
    // 先获取用户的token

    Options header = Options(headers: {"token": Config.getInstance().getToken()});
    Dio dio = new Dio() ;

    var name = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
    var postData = FormData.fromMap({
      "file": await MultipartFile.fromFile(
          file.path, filename: name)
    });

    if(url.startsWith("/")) {
      url = url.substring(1) ;
    }

    try {
      print(Config.getInstance().getHost()+url) ;
      var responce = await Dio().post(Config.getInstance().getHost() + url,data:postData,onSendProgress: (int sent, int total) {
        //  print("$sent $total"); //send是上传的大小 total是总文件大小
        if(onProcess != null){
          onProcess(sent / total) ;
        }
      },options: header).catchError((res){
        print("报错了") ;
        print(res) ;
      }) ;
      if(responce == null) {
        return {"code":500 , "msg":"网络繁忙!" , "data":""} ;
      }
      return responce.data ;
    } catch (e) {
      print(e) ;
      return {"code":500 , "msg":"网络连接异常" , "data":""} ;
    } finally{
      dio.close() ;
    }
  }


  Future<dynamic> post(String url ,Map<String,dynamic> postdata) async{
    // 先获取用户的token
    String token = Config.getInstance().getToken() ;
    BaseOptions header = BaseOptions(headers: {"token": token});
    Dio dio = new Dio(header) ;

    try {
      print(Config.getInstance().host + url) ;
      var responce = await dio.post(Config.getInstance().host + url,data:postdata).catchError((res){
        print("报错了") ;
      }) ;
      if(responce == null) {
        return {"code":500 , "msg":"网络繁忙!" , "data":""} ;
      }
      return responce ;
    } catch (e) {
      print(e) ;
      return {"code":500 , "msg":"网络连接异常" , "data":""} ;
    } finally{
      dio.close() ;
    }
  }
}
